package com.ytt.core.util.jpa;

import com.ytt.core.util.SpringUtil;
import com.ytt.core.util.generator.Snowflake;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Properties;

/**
 * SnowflakeIdGenerator
 *
 * @author chenwen
 * @date 2019/9/12 15:14
 */
public class SnowflakeIdGenerator  implements IdentifierGenerator, Configurable {
    private Snowflake snowflake;
    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        if (snowflake == null) {
            this.snowflake = (Snowflake) SpringUtil.getBean("snowflake");
            if (this.snowflake == null) {
                throw new HibernateException("Cannot create SnowflakeIdGenerator!");
            }
        }

        return snowflake.nextId();
    }
    /**
     * 加载配置文件中的数据初始化Snowflake类
     */
    @Override
    public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
        //加载配置文件
        InputStream is = SnowflakeIdGenerator.class.getResourceAsStream("/snowflake.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
            throw new HibernateException("加载snowflake文件异常" + e.getMessage());
        }
        String  workId = properties.getProperty("workId");
        String dataId = properties.getProperty("dataId");
        if (StringUtils.isNotBlank(dataId) && StringUtils.isNotBlank(workId)) {
            snowflake = new Snowflake(Long.valueOf(workId), Long.valueOf(dataId));
        }
    }

    
}
